package test;

import javax.swing.*;
import javax.swing.table.DefaultTableModel;
import java.awt.event.*;
import java.sql.*;

public class DatabaseMenuExample {
    public static void main(String[] args) {
        SwingUtilities.invokeLater(new Runnable() {
            @Override
            public void run() {
                createAndShowGUI();
            }
        });
    }

    private static void createAndShowGUI() {
        JFrame frame = new JFrame("数据库菜单示例");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setSize(600, 400);

        JMenuBar menuBar = new JMenuBar();
        JMenu databaseMenu = new JMenu("数据库");
        JMenuItem showEmployeesItem = new JMenuItem("展示员工信息");

        showEmployeesItem.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                showDatabaseTable("tb_employee"); // 展示员工信息
            }
        });

        databaseMenu.add(showEmployeesItem);
        menuBar.add(databaseMenu);
        frame.setJMenuBar(menuBar);

        frame.setVisible(true);
    }

    private static void showDatabaseTable(String tableName) {
        // 数据库连接信息
        String url = "jdbc:mysql://localhost:3306/test?useSSL=false&serverTimezone=UTC";
        String user = "root";
        String password = "123456";

        // 直接在查询中使用表名，不使用参数化查询
        String query = "SELECT * FROM " + tableName;

        try {
            Connection conn = DriverManager.getConnection(url, user, password);
            Statement stmt = conn.createStatement();
            ResultSet rs = stmt.executeQuery(query);

            // 从ResultSet获取列名
            ResultSetMetaData metaData = rs.getMetaData();
            int columnCount = metaData.getColumnCount();
            String[] columnNames = new String[columnCount];
            for (int i = 0; i < columnCount; i++) {
                columnNames[i] = metaData.getColumnName(i + 1); // 列索引从1开始
            }

            // 创建数据模型并填充数据
            DefaultTableModel model = new DefaultTableModel(columnNames, 0);
            while (rs.next()) {
                Object[] row = new Object[columnCount];
                for (int i = 0; i < columnCount; i++) {
                    row[i] = rs.getObject(i + 1); // 行数据索引从1开始
                }
                model.addRow(row);
            }

            // 创建JTable并设置模型
            JTable table = new JTable(model);

            // 显示JTable
            JFrame tableFrame = new JFrame(tableName);
            tableFrame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
            tableFrame.add(new JScrollPane(table));
            tableFrame.pack();
            tableFrame.setLocationRelativeTo(null); // 居中显示
            tableFrame.setVisible(true);

        } catch (SQLException ex) {
            JOptionPane.showMessageDialog(null, "数据库连接或查询失败: " + ex.getMessage());
            ex.printStackTrace();
        }
    }
}
